package com.example.demo.common;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 *全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    public R<String> excepitonHandler(MySQLIntegrityConstraintViolationException mex){
        log.error(mex.getMessage());
        if(mex.getMessage().contains("Duplicate entry")){
            String[] split = mex.getMessage().split(" ");
            String msg = split[2] + "已经存在，请更换";
            return R.error(msg);
        }
        return R.error("未知错误");

    }
}
